import services from '@/services/user';
import { message } from 'antd';
import { GModalButton, GTable, GTableSchema } from 'geminis-react';
import { useCallback, useRef } from 'react';

const { updateRole } = services.UserController;

export const UserRole = (props: {
  user: any;
  onSubmitted: () => void;
}) => {
  const table = useRef<any>();

  const save = useCallback((): Promise<any> => {
    return updateRole(props.user.id, table.current.selection.selectedKeys)
      .then((resp) => {
          message.success('成功');
          props.onSubmitted?.();
          return resp;
        },
      ).catch(err => {
        message.error('保存失败');
      });
  }, []);

  const schema: GTableSchema = {
    data: {
      url: '/api/resources/role',
      sort: 'name:asc',
    },
    rowSelection: {
      defaultSelectedRowKeys: props.user?.roles?.map((role: any) => role.id),
    },
  };

  return (
    <GModalButton
      text="设置角色"
      button={{
        type: 'link',
      }}
      onOk={save}
    >
      <GTable
        ref={table}
        schema={schema}
        schemaPath="/resources-pc/schema/user/table-role.json"
      />
    </GModalButton>
  );
};
